package com.lly.tboc.zhouyi.vm

import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Environment
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lly.tboc.zhouyi.db.ZhouyiDb
import com.lly.tboc.zhouyi.vo.Gua
import com.lly.tboc.zhouyi.vo.Yao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import javax.inject.Inject

@HiltViewModel
class GuaViewModel @Inject constructor(
    val application: Application,
    val db: ZhouyiDb,
) : ViewModel() {
    fun get(): Flow<List<Gua>> {
        return db.guaDao().get().flowOn(Dispatchers.IO)
    }

    suspend fun getYao(guaId: Int, yaoId: Int): Yao? {
        return db.yaoDao().get(guaId, yaoId)
    }

    suspend fun getPositionByGuaId(guaId: Int): Int {
        return get().first().indexOfFirst { it.id == guaId }
    }

    val showShareButtonState = mutableStateOf("")

    fun doShare(context: Context) {
        try {
            val intent = Intent(Intent.ACTION_SEND)
            val uri = FileProvider.getUriForFile(
                context,
                "${context.packageName}.fileprovider",
                File(showShareButtonState.value)
            )
            intent.setType("text/plain")
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            intent.putExtra(Intent.EXTRA_STREAM, uri) // 添加附件，附件为file对象
            context.startActivity(intent) // 调用系统的mail客户端进行发送
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    fun saveZhouYiToFile() {
        viewModelScope.launch(Dispatchers.IO) {
            val dir = application.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val path = File(dir, "zhouyi.md")
            path.outputStream().bufferedWriter().use { file ->
                db.guaDao().get().firstOrNull()?.let { guas ->
                    file.append("# 周易\n")
                    guas.forEach { gua ->
                        file.append(gua.toDataForString())
                        file.newLine()
                        db.yaoDao().get(gua.id).forEach { yao ->
                            file.append(yao.toDataForString())
                            file.newLine()
                        }
                    }
                }
            }

            withContext(Dispatchers.Main) {
                showShareButtonState.value = path.absolutePath
                delay(3000)
                showShareButtonState.value = ""
            }
        }
    }

    fun search(query: String): Flow<List<Gua>> {
        return db.searchDao().search(query).flowOn(Dispatchers.IO)
    }

}